package com.yonyou.brigade.controller;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IDeveloperService;
import com.yonyou.brigade.order_center.model.ThirdResult;
import com.yonyou.brigade.third_parties.ctripBC.service.ICtripBCPublicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/cron")
public class SyncUserController {

    private static Logger logger = LoggerFactory.getLogger(SyncUserController.class);

    @Value("${brigade.cur}")
    private String curEnv;

    @Autowired
    private IBriChannelService briChannelService;

    @Autowired
    private IDeveloperService developerService;

    @Autowired
    private ICtripBCPublicService ctripBCPublicService;

    @RequestMapping("/user/syncUsersToCtripBC")
    public ThirdResult syncUsersToCtripBC(@RequestBody JSONObject param) {
        ThirdResult thirdResult = new ThirdResult();
        thirdResult.setSuccess(Boolean.FALSE);
        if (param != null && "yonyou@1988".equals(param.getString("token"))) {
            String tenantId = param.getString("tenantId");
            String orgPk = param.getString("orgPk");
            Integer openType = param.getInteger("openType");
            List<BriChannel> briChannels = briChannelService.getEnableChannelByOpenTypeAndOrgAndTenant(tenantId, orgPk, openType);
            if (CollectionUtils.isEmpty(briChannels)){
                thirdResult.setMsg("请确认是否已进行商旅开通");
                return thirdResult;
            }
            for (BriChannel briChannel : briChannels) {
                try {
                    ctripBCPublicService.syncAllUsersToCtripBC(tenantId, orgPk, openType, briChannel);
                } catch (Exception e){
                    logger.error(tenantId + "租户" + briChannel.getChannel() + "渠道（渠道id为" + briChannel.getId() + "）同步人员失败");
                    developerService.sendEmailToDev(curEnv, briChannel.getChannel(), "同步人员", e);
                }
            }
        } else {
            thirdResult.setMsg("token校验失败");
            return thirdResult;
        }
        thirdResult.setSuccess(Boolean.TRUE);
        thirdResult.setMsg("同步成功");
        return thirdResult;
    }
}
